package com.csoa.community.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.csoa.community.R;
import com.csoa.community.bean.AttachBean;
import com.csoa.community.bean.OffDocComWordBean;
import com.csoa.community.bean.OffDocDetailBean;
import com.csoa.community.net.WcfAsyncTask;
import com.csoa.community.requests.AbstractRequest;
import com.csoa.community.requests.ComWordRequest;
import com.csoa.community.requests.OffDocAttachRequest;
import com.csoa.community.requests.OffDocDetailMeetingRequest;
import com.csoa.community.requests.OffDocDetailRequest;
import com.csoa.community.requests.OffDocDetailSubmitRequest;
import com.csoa.community.requests.OffDocDirectForwardRequest;
import com.csoa.community.requests.OffDocDownLoadAttachRequest;
import com.csoa.community.services.DownLoadAttachService;
import com.csoa.community.services.UpgradeService;
import com.csoa.community.singletons.GlobalVars;
import com.csoa.community.utils.AndroidUtils;
import com.csoa.community.utils.Json;
import com.csoa.community.utils.StringUtils;
import com.csoa.community.widget.CommonDialog;
import com.csoa.community.widget.CommonDialog.OnListItemClickListener;
import com.csoa.community.widget.CommonDialog.OnRefreshListener;
import com.csoa.community.widget.PullToRefreshScrollView;

public class OffDocDetailActivity extends BaseActivity {

	private Button mOffDetailBtn;
	private LinearLayout mOffDetailLayout;
	private TextView mOffDetailDisNameTV;
	private TextView mOffDetailRececiveCodeTV;
	private TextView mOffDetailFromCodeTV;
	private TextView mOffDetailCreateDateTV;
	private TextView mOffDetailImportGradeTV;
	private TextView mOffDetailFromTV;
	private TextView mOffDetailTitleTV;
	private TextView mOffDetailContentTV;
	private TextView mOffDetailAttachTV;
	private TextView mOffDetailStartTimeTV;
	private TextView mOffDetailEndTimeTV;
	private TextView mOffDetailImportantTV;
	private TextView mOffDetailAddressTV;
	private CheckBox mOffDetailAttendMeetingCheck;
	private LinearLayout mOffDetailMeetingLayout;
	private LinearLayout mOffDetailAttendMeetingLayout;
	private String RID;
	private String ID;
	private LinearLayout mOffDetailAttachLayout;
	private TextView mOffDetailCommonLanguageBtn;
	private EditText mOffDetailCommonLanguageET;
	// 判断是否是签批(如果点击签批按钮 issued = true，否则是false)
	private boolean issued;
	private LinearLayout mOffDetailAttachTotalLayout;
	private EditText mOffDetailChooseAddresseeET;
	private Button mOffDetailChooseAddresseeBtn;
	private RadioButton mOffDocDirectOfficeCheck;
	private RadioButton mOffDocContinueCheck;
	private RadioGroup mOffDocForwardRadioGroup;
	private Button mOffDetailSubmitBtn;
	private Button mOffDetailCancelBtn;

	// 收件人姓名
	protected String mDisName;
	protected String mGUID;
	private int mIsAddMetting = 0;
	private boolean isupdate;
	private String readType;
	private LinearLayout mOffDetailForwardLayout;
	protected boolean isRefreshComWord;
	private CommonDialog caculatorDialog;
	private boolean isMeeting;
	protected DownLoadAttachService service;
	private RelativeLayout mOffDetailSubmitLayout;
	private HashMap<String, OffDocDetailBean> contents;
	protected OffDocDetailBean mOffDetailBean;
	private Button moffDetailPreBtn;
	private Button mOffDetailNextBtn;
	private int mPosition;
	private AsyncTask<AbstractRequest, Object, AbstractRequest> detailTask;
	private AsyncTask<AbstractRequest, Object, AbstractRequest> attachTask;
	private PullToRefreshScrollView mPulldocDetailScroll;
	private ScrollView docDetailScroll;
	public static final int AddresseeRequestCode = 3;
	LayoutInflater inflater;
	private View mScollerContentView;
	private String mApproval;
	private TextView mTVApproval;
	private TextView mTVHaveReadApproval;

	@Override
	public void initUI() {
		setContentView(R.layout.ui_official_doc_detail);
		inflater = LayoutInflater.from(this);
		mPulldocDetailScroll = (PullToRefreshScrollView) this
				.findViewById(R.id.docDetailScroll);

		mPulldocDetailScroll
				.setMode(PullToRefreshScrollView.MODE_PULL_DOWN_TO_REFRESH);
		mPulldocDetailScroll
				.setOnRefreshListener(new PullToRefreshScrollView.OnRefreshListener() {

					@Override
					public void onRefresh() {
						buildRequestDetail(ID, RID);
					}
				});

		docDetailScroll = mPulldocDetailScroll.refreshableView;
		mScollerContentView = inflater.inflate(
				R.layout.ui_official_doc_detail_scroller, null);
		docDetailScroll.addView(mScollerContentView);

		// 详细按钮
		mOffDetailBtn = (Button) this.findViewById(R.id.offDetailBtn);
		mOffDetailLayout = (LinearLayout) this
				.findViewById(R.id.offDetailLayout);
		mOffDetailDisNameTV = (TextView) this
				.findViewById(R.id.offDetailDisNameTV);
		mOffDetailRececiveCodeTV = (TextView) this
				.findViewById(R.id.offDetailRececiveCodeTV);
		mOffDetailFromCodeTV = (TextView) this
				.findViewById(R.id.offDetailFromCodeTV);
		mOffDetailCreateDateTV = (TextView) this
				.findViewById(R.id.offDetailCreateDateTV);
		mOffDetailImportGradeTV = (TextView) this
				.findViewById(R.id.offDetailImportGradeTV);

		mOffDetailFromTV = (TextView) this.findViewById(R.id.offDetailFromTV);
		// 标题
		mOffDetailTitleTV = (TextView) this.findViewById(R.id.offDetailTitleTV);
		// 内容
		mOffDetailContentTV = (TextView) this
				.findViewById(R.id.offDetailContentTV);
		// 附件
		mOffDetailAttachTV = (TextView) this
				.findViewById(R.id.offDetailAttachTV);
		// 会议layout
		mOffDetailMeetingLayout = (LinearLayout) this
				.findViewById(R.id.offDetailMeetingLayout);
		// 是否参加会议确认layout
		mOffDetailAttendMeetingLayout = (LinearLayout) this
				.findViewById(R.id.offDetailAttendMeetingLayout);
		mOffDetailStartTimeTV = (TextView) this
				.findViewById(R.id.offDetailStartTimeTV);
		mOffDetailEndTimeTV = (TextView) this
				.findViewById(R.id.offDetailEndTimeTV);
		mOffDetailImportantTV = (TextView) this
				.findViewById(R.id.offDetailImportantTV);
		mOffDetailAddressTV = (TextView) this
				.findViewById(R.id.offDetailAddressTV);
		mOffDetailAttendMeetingCheck = (CheckBox) this
				.findViewById(R.id.offDetailAttendMeetingCheck);

		mOffDetailAttendMeetingCheck
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) {
							mIsAddMetting = 1;
						} else {
							mIsAddMetting = 0;
						}

					}
				});
		// 详情按钮点击
		mOffDetailBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mOffDetailLayout.getVisibility() == View.VISIBLE) {
					mOffDetailLayout.setVisibility(View.GONE);
					mOffDetailBtn.setText("详细");
				} else {
					mOffDetailLayout.setVisibility(View.VISIBLE);
					mOffDetailBtn.setText("隐藏");
				}
			}
		});

		mOffDetailCommonLanguageBtn = (TextView) this
				.findViewById(R.id.offDetailCommonLanguageBtn);
		mOffDetailCommonLanguageET = (EditText) this
				.findViewById(R.id.offDetailCommonLanguageET);

		mOffDetailChooseAddresseeET = (EditText) this
				.findViewById(R.id.offDetailChooseAddresseeET);

		mOffDetailChooseAddresseeBtn = (Button) this
				.findViewById(R.id.offDetailChooseAddresseeBtn);

		mOffDetailChooseAddresseeBtn
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(OffDocDetailActivity.this,
								LinkmanActivity.class);
						startActivityForResult(intent, 0);
					}
				});

		mOffDocDirectOfficeCheck = (RadioButton) this
				.findViewById(R.id.offDocDirectOfficeCheck);
		mOffDocContinueCheck = (RadioButton) this
				.findViewById(R.id.offDocContinueCheck);
		mOffDocForwardRadioGroup = (RadioGroup) this
				.findViewById(R.id.offDocForwardRadioGroup);
		mOffDocForwardRadioGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						if (checkedId == R.id.offDocDirectOfficeCheck) {
							netRequestDirect(new OffDocDirectForwardRequest());
						} else if (checkedId == R.id.offDocContinueCheck) {
							mOffDetailChooseAddresseeBtn
									.setVisibility(View.VISIBLE);
							mOffDetailChooseAddresseeET.setText("");
						}
					}
				});

		mOffDetailSubmitBtn = (Button) this
				.findViewById(R.id.offDetailSubmitBtn);
		mOffDetailSubmitBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				checkAndSubmit();
			}
		});

		mOffDetailCancelBtn = (Button) this
				.findViewById(R.id.offDetailCancelBtn);
		mOffDetailCancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		// 点击已读列表item，隐藏转发layout
		mOffDetailForwardLayout = (LinearLayout) this
				.findViewById(R.id.offDetailForwardLayout);

		// 提交按钮layout
		mOffDetailSubmitLayout = (RelativeLayout) this
				.findViewById(R.id.offDetailSubmitLayout);

		// 附件layout（包括附件的标题）
		mOffDetailAttachTotalLayout = (LinearLayout) this
				.findViewById(R.id.offDetailAttachTotalLayout);

		// 附件layout
		mOffDetailAttachLayout = (LinearLayout) this
				.findViewById(R.id.offDetailAttachLayout);

		// 常用语点击
		mOffDetailCommonLanguageBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (isRefreshComWord) {
					buildComRequest(GlobalVars.currentUser.loginName);
					return;
				}

				String jsonComWord = AndroidUtils.getGlobal("ComWord",
						"strComWord", OffDocDetailActivity.this);
				if (!StringUtils.isEmpty(jsonComWord)) {

					Json json = new Json(jsonComWord);
					List<OffDocComWordBean> comWords = new ArrayList<OffDocComWordBean>();
					new ComWordRequest().fillAttachList(json, comWords);
					showDialog(comWords);
					return;
				}
				buildComRequest(GlobalVars.currentUser.loginName);
			}
		});

		moffDetailPreBtn = (Button) this.findViewById(R.id.offDetailPreBtn);
		moffDetailPreBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mPosition == 0) {
					showToast("没有更多邮件了");
					return;
				}
				stopTask();
				mScollerContentView.setVisibility(View.INVISIBLE);
				mOffDetailAttachLayout.removeAllViews();
				if (readType.equals(GlobalVars.READ_TYPE_TO_BE_READ)) {
					ID = OfficialDocActivity.mToBeReadOfficialDocs
							.get(mPosition - 1).ID;
					RID = OfficialDocActivity.mToBeReadOfficialDocs
							.get(mPosition - 1).RID;
				} else {
					ID = OfficialDocActivity.mHaveReadOfficialDocs
							.get(mPosition - 1).ID;
					RID = OfficialDocActivity.mHaveReadOfficialDocs
							.get(mPosition - 1).RID;
				}
				mPosition--;

				if (!contents.containsKey(ID)) {
					buildRequestMeeting(ID, RID);
					// buildRequestDetail(ID, RID);
				} else {
					mOffDetailBean = contents.get(ID);
					showOrHiddenLayout(mOffDetailBean);
					setDataToView(mOffDetailBean);
					setDataToAttachView(mOffDetailBean.attachs);
				}

				docDetailScroll.scrollTo(0, 0);

			}
		});

		mOffDetailNextBtn = (Button) this.findViewById(R.id.offDetailNextBtn);
		mOffDetailNextBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (readType.equals(GlobalVars.READ_TYPE_TO_BE_READ)) {
					if (mPosition == OfficialDocActivity.mToBeReadOfficialDocs
							.size() - 1) {
						showToast("没有更多公文了");
						return;
					}

				} else if (mPosition == OfficialDocActivity.mHaveReadOfficialDocs
						.size() - 1) {
					showToast("没有更多公文了");
					return;
				}

				stopTask();
				mScollerContentView.setVisibility(View.INVISIBLE);
				mOffDetailAttachLayout.removeAllViews();
				// mEmailReadStateBtn.setOnClickListener(null);
				if (readType.equals(GlobalVars.READ_TYPE_TO_BE_READ)) {
					ID = OfficialDocActivity.mToBeReadOfficialDocs
							.get(mPosition + 1).ID;
					RID = OfficialDocActivity.mToBeReadOfficialDocs
							.get(mPosition + 1).RID;
				} else {
					ID = OfficialDocActivity.mHaveReadOfficialDocs
							.get(mPosition + 1).ID;
					RID = OfficialDocActivity.mHaveReadOfficialDocs
							.get(mPosition + 1).RID;
				}
				mPosition++;

				if (!contents.containsKey(ID)) {
					// showOrHiddenLayout(mOffDetailBean);
					// buildRequestDetail(ID, RID);
					buildRequestMeeting(ID, RID);
				} else {
					mOffDetailBean = contents.get(ID);
					showOrHiddenLayout(mOffDetailBean);
					setDataToView(mOffDetailBean);
					setDataToAttachView(mOffDetailBean.attachs);
				}

				docDetailScroll.scrollTo(0, 0);
			}
		});

		// 批复意见
		mTVApproval = (TextView) this.findViewById(R.id.offDetailApproval);

		// 批复意见
		mTVHaveReadApproval = (TextView) this.findViewById(R.id.offHaveReadDetailApproval);

	}

	private void stopTask() {
		if (detailTask != null) {
			detailTask.cancel(true);
		}

		if (attachTask != null) {
			attachTask.cancel(true);
		}
	}

	protected void checkAndSubmit() {
		String comWord = mOffDetailCommonLanguageET.getText().toString();
		String addressee = mOffDetailChooseAddresseeET.getText().toString();
		// if (StringUtils.isEmpty(comWord)) {
		// showToast("请填写阅读意见");
		// return;
		// }

		if (StringUtils.isEmpty(addressee)) {
			showToast("请填写收件人");
			return;
		}

		if (StringUtils.isEmpty(mGUID)) {
			showToast("收件人获取失败，请重新选择收件人");
			return;
		}

		submit(comWord, addressee, GlobalVars.currentUser.loginName,
				mIsAddMetting);

	}

	/**
	 * 待阅公文提交
	 * 
	 * @param comWord
	 *            常用语
	 * @param addressee
	 *            收件人
	 * @param aUsername
	 *            登录名
	 * @param IsAddMetting
	 *            是否参加会议
	 */
	private void submit(String comWord, String addressee, String aUsername,
			int IsAddMetting) {
		showProgress();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("LogName", aUsername));
		params.add(new BasicNameValuePair("RID", RID));
		params.add(new BasicNameValuePair("Content", comWord));
		params.add(new BasicNameValuePair("UserGuid", mGUID));
		params.add(new BasicNameValuePair("UserDisName", addressee));
		params.add(new BasicNameValuePair("IsAddMetting", IsAddMetting + ""));

		OffDocDetailSubmitRequest detailSubmitRequest = new OffDocDetailSubmitRequest(
				readType, params);

		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				OffDocDetailSubmitRequest detailCallBackRequest = (OffDocDetailSubmitRequest) request;
				if (detailCallBackRequest.success != null
						&& !"0".equals(detailCallBackRequest.success)) {
					OffDocDetailActivity.this.showToast("提交成功");
					OffDocDetailActivity.this.setResult(RESULT_OK);
					finish();
				} else {
					OffDocDetailActivity.this.showToast("提交失败");
				}

			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				OffDocDetailActivity.this.showToast(msg);
			}
		}).execute(detailSubmitRequest);

	}

	/**
	 * 直接转发办公室,获取特定收件人
	 * 
	 * @param aOffDocDirectForwardRequest
	 */
	protected void netRequestDirect(
			OffDocDirectForwardRequest aOffDocDirectForwardRequest) {
		showProgress();
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				OffDocDirectForwardRequest directForwardRequest = (OffDocDirectForwardRequest) request;
				if (!StringUtils.isEmpty(directForwardRequest.DisName)) {

					mDisName = directForwardRequest.DisName;
					mGUID = directForwardRequest.GUID;
					mOffDetailChooseAddresseeET
							.setText(directForwardRequest.DisName);
					mOffDetailChooseAddresseeBtn.setVisibility(View.GONE);
				}

			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				OffDocDetailActivity.this.showToast(msg);
			}
		}).execute(aOffDocDirectForwardRequest);
	}

	/**
	 * 根据是否是快速签发，显示或隐藏部分view
	 * 
	 * @param visibility
	 */
	public void showOrHiddenToBeRead(int visibility) {
		mOffDetailBtn.setVisibility(visibility);
		mOffDetailTitleTV.setVisibility(visibility);
		mOffDetailContentTV.setVisibility(visibility);
		// mOffDetailAttachTotalLayout.setVisibility(visibility);
	}

	@Override
	public void initData() {
		contents = new HashMap<String, OffDocDetailBean>();
		mPosition = this.getIntent().getIntExtra("position", 0);
		ID = this.getIntent().getStringExtra("ID");
		RID = this.getIntent().getStringExtra("RID");
		readType = this.getIntent().getStringExtra(GlobalVars.READ_TYPE);
		issued = this.getIntent().getBooleanExtra(GlobalVars.ISSUED, false);
		isupdate = this.getIntent().getBooleanExtra(GlobalVars.ISUPDATE, false);
		isMeeting = this.getIntent().getBooleanExtra("isMeeting", false);
		mApproval = this.getIntent().getStringExtra("Approval");
		mOffDetailBean = new OffDocDetailBean();
		mOffDetailBean.isMeeting = isMeeting;
		mOffDetailBean.ID = ID;
		mOffDetailBean.RID = RID;
		if (!StringUtils.isEmpty(mApproval)) {
			mTVApproval.setText(mApproval);
			mTVHaveReadApproval.setText(mApproval);
		} else {
			this.findViewById(R.id.offApprovalLayout).setVisibility(View.GONE);
			this.findViewById(R.id.offHaveReadApprovalLayout).setVisibility(View.GONE);
		}

		if (!contents.containsKey(ID)) {
			showOrHiddenLayout(mOffDetailBean);
			buildRequestDetail(ID, RID);
		} else {
			mOffDetailBean = contents.get(ID);
			showOrHiddenLayout(mOffDetailBean);
			setDataToView(mOffDetailBean);
		}

		// buildRequestDetail(ID, RID);
	}

	private void showOrHiddenLayout(OffDocDetailBean aOffDetailBean) {
		if (!aOffDetailBean.isMeeting) {
			mOffDetailMeetingLayout.setVisibility(View.GONE);
			mOffDetailAttendMeetingLayout.setVisibility(View.GONE);
		} else {
			mOffDetailMeetingLayout.setVisibility(View.VISIBLE);
			mOffDetailAttendMeetingLayout.setVisibility(View.VISIBLE);
		}

		if (readType.equals(GlobalVars.READ_TYPE_TO_BE_READ)) {
			if (issued) {
				showOrHiddenToBeRead(View.GONE);
				if (!aOffDetailBean.isMeeting) {
					return;// 如果不是会议，结束联网请求
				}
			} else {
				showOrHiddenToBeRead(View.VISIBLE);
			}
		} else {
			if (!isupdate) {
				mOffDetailForwardLayout.setVisibility(View.GONE);
				mOffDetailSubmitLayout.setVisibility(View.GONE);
				if (!StringUtils.isEmpty(mApproval)) {
					this.findViewById(R.id.offHaveReadApprovalLayout).setVisibility(View.VISIBLE);
				} 
			}
		}
	}

	/**
	 * 获取详情页数据（构建详情页数据Request）
	 * 
	 * @param request
	 */
	protected void buildRequestDetail(String ID, String RID) {
		// showProgress();
		mPulldocDetailScroll.showHeadView();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("ID", ID));
		params.add(new BasicNameValuePair("RID", RID));
		netRequestDetail(new OffDocDetailRequest(params));
	}

	/**
	 * 获取详情页数据
	 * 
	 * @param request
	 */
	private void netRequestDetail(AbstractRequest request) {
		detailTask = new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				mPulldocDetailScroll.onRefreshComplete();
				dismisProgress();
				OffDocDetailRequest detailRequest = (OffDocDetailRequest) request;
				if (detailRequest.offDocDetailBean != null) {
					mOffDetailBean = detailRequest.offDocDetailBean;
					mOffDetailBean.ID = ID;
					mOffDetailBean.RID = RID;
					mOffDetailBean.isMeeting = isMeeting;
					contents.remove(ID);
					contents.put(ID, detailRequest.offDocDetailBean);

					setDataToView(detailRequest.offDocDetailBean);
					// 不是签发就请求附件
					if (!issued) {
						buildAttachRequest(RID);
					}
				}
			}

			@Override
			public void onCancel() {
				mPulldocDetailScroll.onRefreshComplete();
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				OffDocDetailActivity.this.showToast(msg);
			}
		});
		detailTask.execute(request);
	}

	/**
	 * 下载附件构建Request
	 * 
	 * @param request
	 */
	protected void buildAttachRequest(String aRID) {
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("RID", RID));
		netRequestAttach(new OffDocAttachRequest(params));
	}

	/**
	 * 下载附件
	 * 
	 * @param request
	 */
	private void netRequestAttach(OffDocAttachRequest request) {
		attachTask = new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				OffDocAttachRequest offDocAttachRequest = (OffDocAttachRequest) request;
				if (offDocAttachRequest.mAttachs != null) {
					mOffDetailBean.attachs = offDocAttachRequest.mAttachs;
					setDataToAttachView(offDocAttachRequest.mAttachs);
				}
			}

			@Override
			public void onCancel() {

			}

			@Override
			public void onProgress(int progress, String msg) {
				OffDocDetailActivity.this.showToast(msg);
			}
		});
		attachTask.execute(request);
	}

	/**
	 * 附件下载完毕之后显示在界面中
	 * 
	 * @param mAttachs
	 */
	protected void setDataToAttachView(List<AttachBean> mAttachs) {
		if (mAttachs == null || mAttachs.size() == 0) {
			mOffDetailAttachTotalLayout.setVisibility(View.GONE);
			return;
		}
		mOffDetailAttachTotalLayout.setVisibility(View.VISIBLE);
		mOffDetailAttachLayout.removeAllViews();
		for (int i = 0; i < mAttachs.size(); i++) {
			final AttachBean attach = mAttachs.get(i);
			TextView text = new TextView(this);
			text.setText("附件" + (i + 1) + ":" + attach.A_Title);
			text.setTextSize(18);
			text.setTextColor(this.getResources().getColor(R.color.attach));
			text.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// OffDocDetailActivity.this.showToast(attach.Id);
					boolean isAttachExists = GlobalVars.getInst()
							.isAttachExists(OffDocDetailActivity.this,
									attach.A_ORIGINAL_FILENAME);
					if (!isAttachExists) {
						if (!AndroidUtils
								.isNetworkValidate(OffDocDetailActivity.this)) {
							OffDocDetailActivity.this
									.showToast("无法检测到网络,检查网络是否开启");
							return;
						}
						buildDownLoadAttachRequest(attach);

					}

				}
			});
			mOffDetailAttachLayout.addView(text);
		}
	}

	private void startService(AttachBean attach) {

		Intent intent = new Intent();
		intent.setClass(this, UpgradeService.class);
		intent.putExtra("ID", attach.Id);
		intent.putExtra("FileType", attach.FileType);
		intent.putExtra("A_ORIGINAL_FILENAME", attach.A_ORIGINAL_FILENAME);
		this.startService(intent);
	}

	private ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			service = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder ibinder) {
			service = ((DownLoadAttachService.DownLoadBinder) ibinder)
					.getService();
		}
	};

	protected void buildDownLoadAttachRequest(AttachBean attach) {
		showProgress();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("RID", RID));
		params.add(new BasicNameValuePair("ID", attach.Id));
		params.add(new BasicNameValuePair("FileType", attach.FileType));
		netRequestDownAttach(new OffDocDownLoadAttachRequest(params), attach);
	}

	private void netRequestDownAttach(OffDocDownLoadAttachRequest request,
			final AttachBean attach) {

		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				OffDocDownLoadAttachRequest downAttachRequest = (OffDocDownLoadAttachRequest) request;
				if (!StringUtils.isEmpty(downAttachRequest.success)
						&& "1".equals(downAttachRequest.success)) {

					OffDocDetailActivity.this
							.showToast("附件后台下载中...,下载完成自动存入CSOA目录中");
					startService(attach);
					// String strFilename = attach.A_ORIGINAL_FILENAME;
					// File file = new File(GlobalVars.getInst().getAttachPath()
					// + strFilename);
					// try {
					// if (!file.exists()) {
					// file.createNewFile();
					// }
					// DataOutputStream dos = new DataOutputStream(
					// new FileOutputStream(file));
					// dos.write(downAttachRequest.success.getBytes());
					// } catch (Exception e) {
					// e.printStackTrace();
					// }
				} else {
					OffDocDetailActivity.this.showToast("获取附件失败,附件可能已经删除");
				}
			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				OffDocDetailActivity.this.showToast(msg);
			}
		}).execute(request);

	}

	/**
	 * 详情页view的数据展示
	 * 
	 * @param aOffDocDetailBean
	 */
	protected void setDataToView(OffDocDetailBean aOffDocDetailBean) {
		// mOffDetailLayout =
		// (LinearLayout)this.findViewById(R.id.offDetailLayout);
		mPulldocDetailScroll.onRefreshComplete();
		mScollerContentView.setVisibility(View.VISIBLE);
		mOffDetailDisNameTV.setText("登记人:" + aOffDocDetailBean.DisName);
		mOffDetailRececiveCodeTV
				.setText("收文号:" + aOffDocDetailBean.ReceiveCode);
		mOffDetailFromCodeTV.setText("来文编号:" + aOffDocDetailBean.Code);
		mOffDetailCreateDateTV.setText("登记日期:" + aOffDocDetailBean.CreateDate);
		mOffDetailImportGradeTV
				.setText("重要程度:" + aOffDocDetailBean.ImportGrade);

		mOffDetailFromTV.setText("来源:" + aOffDocDetailBean.FromDept);
		mOffDetailTitleTV.setText("标题:  " + aOffDocDetailBean.Title);
		mOffDetailContentTV.setText("内容:  " + aOffDocDetailBean.Memo);
		// mOffDetailAttachTV.setText("");

		mOffDetailStartTimeTV.setText("会议时间始:" + aOffDocDetailBean.StartTime);
		mOffDetailEndTimeTV.setText("会议时间终:" + aOffDocDetailBean.EndTime);
		mOffDetailAddressTV.setText("会议地址:" + aOffDocDetailBean.Address);
		mOffDetailImportantTV.setText("会议级别:" + aOffDocDetailBean.Important);

	}

	/**
	 * 获取常用语(构建Request)
	 * 
	 * @param aLogName
	 */
	protected void buildComRequest(String aLogName) {
		if (isRefreshComWord) {
			showProgress();
		}
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("LogName", aLogName));
		netRequestCom(new ComWordRequest(this, params));
	}

	/**
	 * 获取常用语
	 * 
	 * @param request
	 */
	private void netRequestCom(ComWordRequest request) {
		new WcfAsyncTask(this, new OnUICallback() {

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				ComWordRequest comWordRequest = (ComWordRequest) request;
				if (comWordRequest.mComWords != null) {
					if (comWordRequest.mComWords.size() == 0) {
						OffDocDetailActivity.this.showToast("暂无常用语信息");
						isRefreshComWord = true;
					}
					showDialog(comWordRequest.mComWords);
				}
			}

			@Override
			public void onCancel() {
				isRefreshComWord = false;
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				OffDocDetailActivity.this.showToast(msg);
			}
		}).execute(request);
	}

	/**
	 * 获取是否是会议（构建是否是会议Request）
	 * 
	 * @param request
	 */
	public void buildRequestMeeting(String ID, String RID) {
		showProgress();
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("ID", ID));
		params.add(new BasicNameValuePair("RID", RID));
		netRequestMeeting(new OffDocDetailMeetingRequest(params));
	}

	/**
	 * 获取是否是会议
	 * 
	 * @param request
	 */
	private void netRequestMeeting(AbstractRequest request) {
		new WcfAsyncTask(this, new OnUICallback() {

			private boolean isMeeting = false;

			@Override
			public void onGetResult(AbstractRequest request) {
				dismisProgress();
				OffDocDetailMeetingRequest meetingRequest = (OffDocDetailMeetingRequest) request;

				if (meetingRequest.success == null
						|| "".equals(meetingRequest.success)) {
					OffDocDetailActivity.this.showToast("获取会议失败，请稍后再试");
					return;
				}

				if (!meetingRequest.success.equals("0")) {
					isMeeting = true;

				}
				mOffDetailBean = new OffDocDetailBean();
				mOffDetailBean.ID = ID;
				mOffDetailBean.RID = RID;
				mOffDetailBean.isMeeting = isMeeting;
				OffDocDetailActivity.this.isMeeting = isMeeting;
				showOrHiddenLayout(mOffDetailBean);
				buildRequestDetail(ID, RID);

			}

			@Override
			public void onCancel() {
				dismisProgress();
			}

			@Override
			public void onProgress(int progress, String msg) {
				dismisProgress();
				OffDocDetailActivity.this.showToast(msg);
			}
		}).execute(request);
	}

	/**
	 * 点击常用语按钮，弹出常用语列表对话框
	 * 
	 * @param aComWords
	 */
	protected void showDialog(List<OffDocComWordBean> aComWords) {
		final String items[] = new String[aComWords.size()];
		for (int i = 0; i < aComWords.size(); i++) {
			OffDocComWordBean comWord = aComWords.get(i);
			items[i] = comWord.CommonWord;
		}

		if (isRefreshComWord) {
			if (caculatorDialog != null) {
				caculatorDialog.notifyDataChanged(items);
			}
			isRefreshComWord = false;
			return;
		}

		caculatorDialog = new CommonDialog(this);
		caculatorDialog.setDialogTitle("常用语");
		caculatorDialog.setItems(items, new OnListItemClickListener() {

			@Override
			public void onListItemClick(int which) {
				mOffDetailCommonLanguageET.setText(items[which]);
			}
		});
		caculatorDialog.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				isRefreshComWord = true;
				buildComRequest(GlobalVars.currentUser.loginName);
			}
		});
		caculatorDialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		if (resultCode == RESULT_OK) {
			String name = intent.getStringExtra("name");
			mGUID = intent.getStringExtra("id");
			if (name != null) {
				mOffDetailChooseAddresseeET.setText(name);
			}
		}
	}

}
